package grpc

import (
	"context"
	pb "kdemo/api"
	"os"

	"github.com/go-kratos/kratos/pkg/conf/env"
	"github.com/go-kratos/kratos/pkg/conf/paladin"
	"github.com/go-kratos/kratos/pkg/naming"
	"github.com/go-kratos/kratos/pkg/naming/etcd"
	"github.com/go-kratos/kratos/pkg/net/rpc/warden"
)

// CancelFunc CancelFunc
var CancelFunc context.CancelFunc

// New new a grpc server.
func New(svc pb.DemoServer) (ws *warden.Server, err error) {
	var (
		cfg warden.ServerConfig
		ct  paladin.TOML
	)
	if err = paladin.Get("grpc.toml").Unmarshal(&ct); err != nil {
		return
	}
	if err = ct.Get("Server").UnmarshalTOML(&cfg); err != nil {
		return
	}
	ws = warden.NewServer(&cfg)
	pb.RegisterDemoServer(ws.Server(), svc)

	ip := "127.0.0.1" // NOTE: 必须拿到您实例节点的真实IP，
	port := "9000"    // NOTE: 必须拿到您实例grpc监听的真实端口，warden默认监听 9000
	hn, _ := os.Hostname()
	dis, _ := etcd.New(nil)
	ins := &naming.Instance{
		Zone:     env.Zone,
		Env:      env.DeployEnv,
		AppID:    pb.AppID,
		Hostname: hn,
		Addrs: []string{
			"grpc://" + ip + ":" + port,
		},
	}
	CancelFunc, err = dis.Register(context.Background(), ins)
	if err != nil {
		panic(err)
	}
	ws, err = ws.Start()

	// 特别注意！！！
	// cancel必须在进程退出时执行！！！
	// log.Info("before cancel")
	// cancel()
	return
}
